import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Flex, Form, type FormProps, Input } from "antd";
import { login } from "@/api";
import { AUTHORIZATION_TOKEN, ROUTE_PATHS } from "@/constants/common";

import { LoginDataType } from "@/types/login";

export default function RegisterForm() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const onFinish: FormProps<LoginDataType>["onFinish"] = (values) => {
    if (loading) return;
    setLoading(true);
    login(values)
      .then(({ token }) => {
        if (token) {
          navigate(ROUTE_PATHS.user);
          localStorage.setItem(`${AUTHORIZATION_TOKEN}`, token);
          setTimeout(() => {
            window.$notification?.success({
              message: "登录成功",
              description: "欢迎回来",
            });
          }, 300);
        }
      })
      .catch((error) => {
        console.log("error: ", error);
        window.$message?.error(error.message);
      })
      .finally(() => setLoading(false));
  };

  const onFinishFailed: FormProps<LoginDataType>["onFinishFailed"] = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Form
      // initialValues={{ mobile: "13138781584", password: "123456" }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item name="mobile" rules={[{ required: true, message: "请输入手机号" }]}>
        <Input addonBefore={<UserOutlined />} placeholder="请输入手机号" />
      </Form.Item>

      <Form.Item name="password" rules={[{ required: true, message: "请输入密码" }]}>
        <Input.Password addonBefore={<LockOutlined />} placeholder="请输入密码" />
      </Form.Item>

      <Form.Item>
        <Flex justify="space-between" gap={16}>
          <Button type="primary" htmlType="submit" block loading={loading}>
            登录
          </Button>
          {/* <Button type="primary" ghost block loading={loading} onClick={() => navigate(ROUTE_PATHS.register)}>
            还没有账号？去注册
          </Button> */}
        </Flex>
      </Form.Item>
    </Form>
  );
}
